import { ref, isRef, onMounted, onBeforeUnmount, watchEffect } from 'vue'

const NAME = 'TechBlog'

function usePageTitle(title) {
  const originalTitle = ref(document.title)

  // 更新网页标题
  const updatePageTitle = () => {
    const titleValue = isRef(title) ? title.value : title
    if (!titleValue) {
      return
    }
    document.title = titleValue + ' - ' + NAME
  }

  if (isRef(title)) {
    watchEffect(updatePageTitle)
  }

  // 在组件挂载时更新网页标题
  onMounted(() => {
    updatePageTitle()
  })

  // 在组件卸载时恢复原始网页标题
  onBeforeUnmount(() => {
    document.title = originalTitle.value
  })

  return {
    updatePageTitle
  }
}

export default usePageTitle
